package ttOrder.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	
	private final static String tableIdCookieName = "tableId"; 
	private final static String userIdCookieName = "userId"; 
	private final static String userRoleCookieName = "userRole"; 
	private final static int cookieTime = 12*60*60;
	
	/**设置cookie的值
	 * 
	 * @param HttpServletResponse,int
	 * 
	 * @author emoker
	 * 
	 * @return 可以不需要返回值*/
	public static void saveUserIdToCookie(HttpServletResponse response,String userId){
		if (response != null && userId != null) {
			try {
				String cookieValue = String.valueOf(userId);
				response = setCookie(response, userIdCookieName, cookieValue, cookieTime);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**通过request获取cookie中用户ID的值
	 * 
	 * @param HttpServletRequest
	 * 
	 * @author emoker
	 * 
	 * @return int*/
	public static String getUserIdFromCookie(HttpServletRequest request){
		String id = null;
		if (request != null && userIdCookieName != null) {
			Cookie cookie = getCookieByName(request, userIdCookieName);
			if (cookie != null) {
				id = cookie.getValue();
			}
		}
		return id;
	}
	
	
	/**设置cookie的值
	 * 
	 * @param HttpServletResponse,int
	 * 
	 * @author emoker
	 * 
	 * @return 可以不需要返回值*/
	public static HttpServletResponse saveUserRoleToCookie(HttpServletResponse response,int userRole){
		if (response != null && userRole > 0) {
			try {
				String cookieValue = String.valueOf(userRole);
				response = setCookie(response, userRoleCookieName, cookieValue, cookieTime);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return response;
	}
	
	/**通过request获取cookie中用户角色的值
	 * 
	 * @param HttpServletRequest
	 * 
	 * @author emoker
	 * 
	 * @return int*/
	public static int getUserRoleFromCookie(HttpServletRequest request){
		int role = 0;
		if (request != null && tableIdCookieName != null) {
			Cookie cookie = getCookieByName(request, userRoleCookieName);
			if (cookie != null) {
				String value = cookie.getValue();
				role = Integer.valueOf(value);
			}
		}
		return role;
	}
	
	/**设置cookie的值
	 * 
	 * @param HttpServletResponse,int
	 * 
	 * @author emoker
	 * 
	 * @return 可以不需要返回值*/
	public static HttpServletResponse saveTableIdToCookie(HttpServletResponse response,int tableId){
		if (response != null && tableId > 0) {
			try {
				int time = 12*60*60;
				String tableIdValue = String.valueOf(tableId);
				response = setCookie(response, tableIdCookieName, tableIdValue, time);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return response;
	}
	
	/**通过request获取cookie的值
	 * 
	 * @param HttpServletRequest
	 * 
	 * @author emoker
	 * 
	 * @return int*/
	public static int getTableIdFromCookie(HttpServletRequest request){
		int id = 0;
		if (request != null && tableIdCookieName != null) {
			Cookie cookie = getCookieByName(request, tableIdCookieName);
			if (cookie != null) {
				String value = cookie.getValue();
				id = Integer.valueOf(value);
			}
		}
		return id;
	}
	
	/**清除cookie的值，并将cookie的时间设置为0
	 * 
	 * @param HttpServletResponse
	 * 
	 * @author emoker
	 * 
	 * @return 可以不需要返回值*/
	public static HttpServletResponse clearTableIdFromCookie(HttpServletResponse response){
		if (response != null ) {
			try {
				int tableId = 0;
				String tableIdValue = String.valueOf(tableId);
				response = setCookie(response, tableIdCookieName, tableIdValue, 0);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return response;
	}
	
	
	/*base method for cookie*/
	/**
     * 根据名字获取cookie
     * 
     * @param request
     * @param name
     *            cookie名字
     * @return Cookie
     */
    public static Cookie getCookieByName(HttpServletRequest request, String name) {
        Map<String, Cookie> cookieMap = ReadCookieMap(request);
        if (cookieMap.containsKey(name)) {
            Cookie cookie = (Cookie) cookieMap.get(name);
            return cookie;
        } else {
            return null;
        }
    }

    /**
     * 将cookie封装到Map里面
     * 
     * @param request
     * @return Map<String, Cookie>
     */
    private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

    /**
     * 保存Cookies
     * 
     * @param response
     *            servlet请求
     * @param value
     *            保存值
     * @author jxf
     */
    public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value,int time) {
        // new一个Cookie对象,键值对为参数
        Cookie cookie = new Cookie(name, value);
        // tomcat下多应用共享
        cookie.setPath("/");
        // 如果cookie的值中含有中文时，需要对cookie进行编码，不然会产生乱码
        try {
            URLEncoder.encode(value, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        cookie.setMaxAge(time);
        // 将Cookie添加到Response中,使之生效
        response.addCookie(cookie); // addCookie后，如果已经存在相同名字的cookie，则最新的覆盖旧的cookie
        return response;
    }
    
}
